package com.wnxy.admin.controller;

import cn.hutool.jwt.JWTUtil;
import com.wnxy.admin.common.util.TokenUtil;
import com.wnxy.admin.dto.TokenDto;
import com.wnxy.admin.dto.TokenRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/token")
public class TokenController {
    @Value("${jwt.signature}")
    private String signature;
    @Value("${jwt.accessTimeout}")
    private Integer accessTimeout;

    @PostMapping("/refresh")
    public ResponseEntity refresh(@RequestBody TokenRequest request) throws ParseException {
        /*如果长令牌为NULL,重新登录*/
        if(!StringUtils.hasLength(request.getRefreshToken())){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        /*如果长令牌为非法令牌*/
        if(!JWTUtil.verify(request.getRefreshToken(),signature.getBytes())){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        /*判断长令牌是否过期*/
        LocalDateTime date = LocalDateTime.parse(TokenUtil.getPayLoad(request.getRefreshToken(),"exp"),
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //过期就重新登录
        if(date.isBefore(LocalDateTime.now())){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        Map<String,Object> payload = new HashMap<>();
        payload.put("staffId", TokenUtil.getPayLoad(request.getRefreshToken(),"staffId"));//用户id
        payload.put("exp", LocalDateTime.now().plusMinutes(accessTimeout).
                format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        String token = TokenUtil.createToken(payload, signature);
        return ResponseEntity.ok(new TokenDto(token,null,null,null));
    }
}
